package com.nebula.api.interceptors;

import cn.hutool.json.JSONUtil;
import com.nebula.api.common.entity.TokenUser;
import com.nebula.api.utils.RedisUtils;
import com.nebula.commons.redis.RedisKeys;
import link.ahsj.core.entitys.ApiModel;
import link.ahsj.core.entitys.CodeMsg;
import link.ahsj.core.exception.ErrorCode;
import link.ahsj.core.utils.http.AhsjHttpUtils;
import link.ahsj.core.utils.str.UrlUtils;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Eastern unbeaten
 * @email chenshiyun2011@163.com
 * @data 2019/3/7
 */
@Log
@Component
public class TokenFilter extends OncePerRequestFilter {

    @Value("${app.filter.path}")
    private String filterPath;


    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS,TRACE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // response.setHeader("Access-Control-Allow-Headers", "X-ACCESS-TOKEN,x-auth-token,Access-Control-Allow-Origin,Authorization,Origin,x-requested-with,Content-Type,Content-Range,Content-Disposition,Content-Description");
        response.setHeader("Access-Control-Allow-Headers", "*");
        String method = request.getMethod();
        System.out.println(method);
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            log.info("OPTIONS-------------------------------放行");
            return;
        }
        String clientIP = AhsjHttpUtils.getIPAddr(request);
        log.info("当前访问ip:" + clientIP);
        String contextPath = request.getContextPath();
        log.info("this contextPath:" + contextPath);
        String requestURI = request.getRequestURI();

        //校验是否是过滤请求
        if (!UrlUtils.checkURL(filterPath, requestURI, contextPath)) {
            // 获取token校验
            String token = request.getHeader(Interceptor.X_AUTH_TOKEN);
            log.info("当前拦截器内访问url:" + contextPath + requestURI + "====================token:" + token);
            if (Objects.isNull(token) || Objects.isNull(redisUtils.get(RedisKeys.getAppToken(token), TokenUser.class))) {
                response.setContentType(MediaType.APPLICATION_JSON_UTF8.getType());
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.getWriter().write(JSONUtil.toJsonStr(ApiModel.error(ErrorCode.LOGIN, CodeMsg.NOT_TOKEN)));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

}
